<?php


define('FEATURETABLE_FEATURED_WEIGHT', 1.175);
define('FEATURETABLE_VERSION', '0.2.2');



/**
 * Register the feature table post type
 */
function cfb_featuretable_register(){
	register_post_type('featuretable',array(
		'labels' => array(
			'name' => __('Feature Tables', 'featuretable'),
			'singular_name' => __('Feature Table', 'featuretable'),
			'add_new' => __('Add New', 'book', 'featuretable'),
			'add_new_item' => __('Add New Feature Table', 'featuretable'),
			'edit_item' => __('Edit Feature Table', 'featuretable'),
			'new_item' => __('New Feature Table', 'featuretable'),
			'all_items' => __('Feature Tables', 'featuretable'),
			'view_item' => __('View Feature Table', 'featuretable'),
			'search_items' => __('Search Feature Tables', 'featuretable'),
			'not_found' =>  __('No Feature Tables found', 'featuretable'),
		),
		'public' => true,
		'has_archive' => false,
		'supports' => array( 'title', 'editor'),
		'menu_icon' => trailingslashit(CVINCLUDES_EZTABLES_URI) . 'images/icon.png',
		'show_in_menu' => 'eztables.php',
	));
}
add_action( 'init', 'cfb_featuretable_register');

/**
 * Add custom columns to featuretable post list in the admin
 * @param $cols
 * @return array
 */
function cfb_featuretable_register_custom_columns($cols){
	unset($cols['title']);
	unset($cols['date']);
	
	$cols['title'] = __('Title', 'featuretable');
	$cols['shortcode'] = __('Shortcode', 'featuretable'); 
	$cols['columns'] = __('Columns', 'featuretable');
	$cols['features'] = __('Features', 'featuretable');	
	$cols['date'] = __('Date', 'featuretable');
	return $cols;
}
add_filter( 'manage_featuretable_posts_columns', 'cfb_featuretable_register_custom_columns');

/**
 * Render the contents of the admin columns
 * @param $column_name
 */
function cfb_featuretable_custom_column($column_name){
	global $post;
	switch($column_name){
	case 'features' :
		$table = get_post_meta($post->ID, 'feature_table', true);
		print count($table['features']);
		break;
	case 'columns' :
		$table = get_post_meta($post->ID, 'feature_table', true);
		print $table['columns'];
		break;
	case 'shortcode' :		
		print '[feature_table id=' . $post->ID . ']';
		break;
	}
}
add_action( 'manage_featuretable_posts_custom_column', 'cfb_featuretable_custom_column');

/**
 * @return string The URL of the CSS file to use
 */
function cfb_featuretable_css_url(){	
	return trailingslashit(CVINCLUDES_EZTABLES_URI) . 'css/featuretable.css';
}

/**
 * Enqueue the featuretable scripts
 */
function cfb_featuretable_scripts(){
	global $post, $featuretable_queued, $featuretable_displayed;
	if(is_singular() && (($post->post_type == 'featuretable') || ($post->post_type != 'featuretable' && preg_match( '#\[ *feature_table([^\]])*\]#i', $post->post_content ))) || !empty($featuretable_displayed)){
		wp_enqueue_style('featuretable',  cfb_featuretable_css_url(), null, FEATURETABLE_VERSION);
		$featuretable_queued = true;
	}
}
add_action('wp_enqueue_scripts', 'cfb_featuretable_scripts');

/**
 * Add administration scripts
 * @param $page
 */
function cfb_featuretable_admin_scripts($page){
	if($page == 'post-new.php' || $page == 'post.php'){
		global $post;
		
		if(!empty($post) && $post->post_type == 'featuretable'){
			// Scripts for building the featuretable
			wp_enqueue_script('placeholder', trailingslashit(CVINCLUDES_EZTABLES_URI) . 'js/placeholder.jquery.js', array('jquery'), '1.1.1', true);
			wp_enqueue_script('jquery-ui');
			wp_enqueue_script('featuretable-admin', trailingslashit(CVINCLUDES_EZTABLES_URI) . 'js/featuretable.build.js', array('jquery'), FEATURETABLE_VERSION, true);
			
			wp_localize_script('featuretable-admin', 'pt_messages', array(
				'delete_column' => __('Are you sure you want to delete this column?', 'featuretable'),
				'delete_feature' => __('Are you sure you want to delete this feature?', 'featuretable'),
			));
			
			wp_enqueue_style('featuretable-admin',  trailingslashit(CVINCLUDES_EZTABLES_URI) . 'css/featuretable.admin.css', array(), FEATURETABLE_VERSION);
			wp_enqueue_style('featuretable-icon',  trailingslashit(CVINCLUDES_EZTABLES_URI) . 'css/featuretable.icon.css', array(), FEATURETABLE_VERSION);
			wp_enqueue_style('jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css', array(), '1.7.0');
		}
	}
	
	// The light weight CSS for changing the icon
	if(@$_GET['post_type'] == 'featuretable'){
		wp_enqueue_style('featuretable-icon',  trailingslashit(CVINCLUDES_EZTABLES_URI) . 'css/featuretable.icon.css', array(), FEATURETABLE_VERSION);
	}
}
add_action('admin_enqueue_scripts', 'cfb_featuretable_admin_scripts');

/**
 * Metaboxes because we're boss
 * 
 * @action add_meta_boxes
 */
function cfb_featuretable_meta_boxes(){
	add_meta_box('featuretable', __('Feature Table', 'featuretable'), 'cfb_featuretable_render_metabox', 'featuretable', 'normal', 'high');
	add_meta_box('featuretable-shortcode', __('Shortcode', 'featuretable'), 'cfb_featuretable_render_metabox_shortcode', 'featuretable', 'side', 'low');
}
add_action( 'add_meta_boxes', 'cfb_featuretable_meta_boxes' );

/**
 * Render the feature table building interface
 * 
 * @param $post
 * @param $metabox
 */
function cfb_featuretable_render_metabox($post, $metabox){
	wp_nonce_field( plugin_basename( __FILE__ ), 'cfb_featuretable_nonce' );
	
	$table = get_post_meta($post->ID, 'feature_table', true);
	if(empty($table)) {$table = array(); $table['features'] = array(); }
	
	include(dirname(__FILE__).'/tpl/featuretable.build.phtml');
}

/**
 * Render the shortcode metabox
 * @param $post
 * @param $metabox
 */
function cfb_featuretable_render_metabox_shortcode($post, $metabox){
	?>
		<code>[feature_table id=<?php print $post->ID ?>]</code>
		<small class="description"><?php _e('Displays feature table on another page.', 'featuretable') ?></small>
	<?php
}

/**
 * Save the feature table
 * @param $post_id
 * @return
 * 
 * @action save_post
 */
function cfb_featuretable_save($post_id){
	// Authorization, verification this is my vocation 
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	if ( !wp_verify_nonce( @$_POST['cfb_featuretable_nonce'], plugin_basename( __FILE__ ) ) ) return;
	if ( !current_user_can( 'edit_post', $post_id ) ) return;
	//echo   "<script> alert('abc'); </script>"; 
	// Create the feature table from the post variables
	$table = array();
	
	$table['columns'] = $_POST['number_columns'];	
	$table['imagealignment'] = $_POST['image_alignment'];	
	
	foreach($_POST as $name => $val){		
			
		if(substr($name,0,8) == 'feature_'){
			$parts = explode('_', $name);			
			$i = intval($parts[1]);
			if(isset($parts[2])){
				// Adding a field
				$table['features'][$i][$parts[2]] = $val;
			}
		}
	}
	
    //$table = array_values($table);
	
	update_post_meta($post_id,'feature_table', $table);
}
add_action( 'save_post', 'cfb_featuretable_save' );

/**
 * The feature table shortcode.
 * @param array $atts
 * @return string
 * 
 * 
 */
function cfb_featuretable_shortcode($atts = array()) {
	global $post, $featuretable_displayed;
	
	$featuretable_displayed = true;
	
	extract( shortcode_atts( array(
		'id' => null,
		'width' => 100,
	), $atts ) );
	
	if($id == null) $id = $post->ID;
	
	$table = get_post_meta($id , 'feature_table', true);
	if(empty($table)) $table = array();
	
	// Set all the classes
	$featured_index = null;
	if(!is_array($table['features'])) return;
	foreach($table['features'] as $i => $column) {
		$table['features'][$i]['classes'] = array('featuretable-column');
		//$table[$i]['classes'][] = (@$table[$i]['featured'] === 'true') ? 'featuretable-featured' : 'featuretable-standard';
		
		//if(@$table[$i]['featured'] == 'true') $featured_index = $i;
		//if(@$table[$i+1]['featured'] == 'true') $table[$i]['classes'][] = 'featuretable-before-featured';
		//if(@$table[$i-1]['featured'] == 'true') $table[$i]['classes'][] = 'featuretable-after-featured';
	}
	$table['features'][0]['classes'][] = 'featuretable-first';
	$table['features'][count($table['features'])-1]['classes'][] = 'featuretable-last';
	
	// Calculate the widths
	$width_total = 0;
	//foreach($table as $i => $column){
	//	if(@$column['featured'] === 'true') $width_total += FEATURETABLE_FEATURED_WEIGHT;
	//	else $width_total++;
	//}
	//$width_sum = 0;
	//foreach($table as $i => $column){
	//	if(@$column['featured'] === 'true'){
			// The featured column takes any width left over after assigning to the normal columns
	//		$table[$i]['width'] = 100 - (floor(100/$width_total) * ($width_total-FEATURETABLE_FEATURED_WEIGHT));
	//	}
	//	else{
	//		$table[$i]['width'] = floor(100/$width_total);
	//	}
	//	$width_sum += $table[$i]['width'];
	//}
	
	// Create fillers
	//if(!empty($table[0]['features'])){
	//	for($i = 0; $i < count($table[0]['features']); $i++){
	//		$has_title = false;
	//		$has_sub = false;
			
	//		foreach($table as $column){
	//			$has_title = ($has_title || !empty($column['features'][$i]['title']));
	//			$has_sub = ($has_sub || !empty($column['features'][$i]['sub']));
	//		}
			
	//		foreach($table as $j => $column){
	//			if($has_title && empty($table[$j]['features'][$i]['title'])) $table[$j]['features'][$i]['title'] = '&nbsp;';
	//			if($has_sub && empty($table[$j]['features'][$i]['sub'])) $table[$j]['features'][$i]['sub'] = '&nbsp;';
	//		}
	//	}
	//}
	
	// Find the best featuretable file to use
	if(file_exists(get_stylesheet_directory().'/featuretable.php')) $template = get_stylesheet_directory().'/featuretable.php';
	elseif(file_exists(get_template_directory().'/featuretable.php')) $template = get_template_directory().'/featuretable.php'; 
	else $template = dirname(__FILE__).'/tpl/featuretable.phtml';
	
	// Render the featuretable
	ob_start();
	include($template);
	$featuretable = ob_get_clean();
	
	//if($width != 100) $featuretable = '<div style="width:45%; margin: 0 auto;">'.$featuretable.'</div>';
	
	$post->featuretable_inserted = true;
	
	return $featuretable;
}
add_shortcode( 'feature_table', 'cfb_featuretable_shortcode' );

/**
 * Add the featuretable to the content.
 * 
 * @param $the_content
 * @return string
 * 
 * @filter the_content
 */
function cfb_featuretable_the_content_filter($the_content){
	global $post;
	
	if(is_single() && $post->post_type == 'featuretable' && empty($post->featuretable_inserted)){
		$the_content = cfb_featuretable_shortcode().$the_content;
	}
	return $the_content;
}
// Filter the content after WordPress has had a chance to do shortcodes (priority 10)
add_filter('the_content', 'cfb_featuretable_the_content_filter',11);

/**
 * @action wp_footer
 */
function cfb_featuretable_footer(){
	global $featuretable_queued, $featuretable_displayed;
	
	if(!empty($featuretable_displayed) && empty($featuretable_queued)){
		$featuretable_queued = true;
		// The featuretable has been rendered, but its CSS not enqueued (happened with some themes)
		?><link rel="stylesheet" type="text/css" href="<?php print cfb_featuretable_css_url() ?>" /><?php
	}
}
add_action('wp_footer', 'cfb_featuretable_footer');
